import { useState, useEffect, useCallback, useRef } from 'react';
import { debounce } from 'lodash';

export type AutoSaveStatus = 
  | 'idle' 
  | 'saving' 
  | 'saved' 
  | 'manually_saved' 
  | 'error'
  | 'conflict'
  | 'pending';

interface AutoSaveOptions {
  projectId: string;
  documentId: string;
  initialContent?: any;
  onSave?: (content: any) => Promise<void>;
  debounceTime?: number;
  enabled?: boolean;
  autoSaveKey?: string; // 本地存储键名
  maxBackupCount?: number; // 最大备份数量
  backupLocalContent?: boolean; // 是否本地备份
}

export function useAutoSave({
  projectId,
  documentId,
  initialContent,
  onSave,
  debounceTime = 2000,
  enabled = true,
  autoSaveKey = 'auto_save',
  maxBackupCount = 5,
  backupLocalContent = true
}: AutoSaveOptions) {
  // 状态
  const [status, setStatus] = useState<AutoSaveStatus>('idle');
  const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null);
  const [documentVersion, setDocumentVersion] = useState<number>(initialContent?.version || 0);
  const [conflictDetected, setConflictDetected] = useState<boolean>(false);
  const [saveAttempts, setSaveAttempts] = useState<number>(0);
  
  // 引用
  const contentRef = useRef<any>(initialContent?.content);
  const lastSavedContentRef = useRef<any>(initialContent?.content);
  const hasUnsavedChanges = useRef<boolean>(false);
  
  // 生成唯一的本地存储键
  const localStorageKey = `${autoSaveKey}_${projectId}_${documentId}`;
  
  // 保存文档到服务器
  const save = useCallback(async (content: any) => {
    console.log('执行保存操作...', { projectId, documentId });
    if (!enabled || !onSave) return;
    
    try {
      setStatus('saving');
      
      // 保存到服务器
      await onSave(content);
      
      // 更新状态
      setStatus('manually_saved');
      setLastSavedAt(new Date());
      lastSavedContentRef.current = content;
      hasUnsavedChanges.current = false;
      setSaveAttempts(0);
      
      console.log('文档保存成功', { documentId });
      
      // 保存成功后，如果有本地备份则清除
      if (typeof window !== 'undefined' && backupLocalContent) {
        localStorage.removeItem(localStorageKey);
      }
      
      return true;
    } catch (error) {
      console.error('文档保存失败:', error);
      setStatus('error');
      
      // 如果是版本冲突
      if (error instanceof Error && error.message.includes('version_conflict')) {
        setConflictDetected(true);
        setStatus('conflict');
      } else {
        // 非冲突错误，增加尝试次数
        setSaveAttempts(prev => prev + 1);
        
        // 备份到本地以防数据丢失
        if (typeof window !== 'undefined' && backupLocalContent) {
          backupContentToLocalStorage(content);
        }
      }
      
      return false;
    }
  }, [projectId, documentId, enabled, onSave, backupLocalContent, localStorageKey]);
  
  // 将内容备份到localStorage
  const backupContentToLocalStorage = useCallback((content: any) => {
    if (!backupLocalContent || typeof window === 'undefined') return;
    
    try {
      // 获取现有备份
      const backupsStr = localStorage.getItem(`${localStorageKey}_backups`);
      const backups = backupsStr ? JSON.parse(backupsStr) : [];
      
      // 添加新备份
      const newBackup = {
        content,
        timestamp: Date.now(),
        version: documentVersion
      };
      
      // 将新备份添加到备份列表的开头
      backups.unshift(newBackup);
      
      // 保留最新的N个备份
      const updatedBackups = backups.slice(0, maxBackupCount);
      
      // 保存回localStorage
      localStorage.setItem(`${localStorageKey}_backups`, JSON.stringify(updatedBackups));
      localStorage.setItem(localStorageKey, JSON.stringify({
        content,
        timestamp: Date.now(),
        version: documentVersion,
        projectId,
        documentId
      }));
      
      console.log('本地备份已创建', { documentId });
    } catch (error) {
      console.error('创建本地备份失败:', error);
    }
  }, [localStorageKey, documentVersion, projectId, documentId, maxBackupCount, backupLocalContent]);
  
  // 节流的自动保存函数
  const debouncedSave = useCallback(
    debounce(async (content: any) => {
      console.log('自动保存触发', { documentId });
      
      // 检查内容是否实际变化
      if (JSON.stringify(lastSavedContentRef.current) === JSON.stringify(content)) {
        console.log('内容未变化，跳过自动保存');
        return;
      }
      
      // 检查是否启用
      if (!enabled) {
        console.log('自动保存已禁用');
        return;
      }
      
      // 更新状态
      setStatus('saving');
      
      try {
        // 如果onSave回调可用，则保存到服务器
        if (onSave) {
          await onSave({
            content,
            version: documentVersion + 1
          });
          
          // 更新版本
          setDocumentVersion(prev => prev + 1);
          
          // 更新状态
          setStatus('saved');
          setLastSavedAt(new Date());
          lastSavedContentRef.current = content;
          hasUnsavedChanges.current = false;
          setSaveAttempts(0);
          
          // 保存成功后，如果有本地备份则清除
          if (typeof window !== 'undefined' && backupLocalContent) {
            localStorage.removeItem(localStorageKey);
          }
          
          console.log('自动保存成功', { documentId });
        }
      } catch (error) {
        console.error('自动保存失败:', error);
        setStatus('error');
        
        // 如果是版本冲突
        if (error instanceof Error && error.message.includes('version_conflict')) {
          setConflictDetected(true);
          setStatus('conflict');
          console.log('检测到版本冲突');
        } else {
          // 非冲突错误，增加尝试次数
          setSaveAttempts(prev => prev + 1);
          
          // 备份到本地以防数据丢失
          if (typeof window !== 'undefined' && backupLocalContent) {
            backupContentToLocalStorage(content);
          }
        }
      }
    }, debounceTime),
    [enabled, onSave, documentVersion, debounceTime, lastSavedContentRef.current]
  );
  
  // 触发自动保存
  const triggerAutoSave = useCallback((content: any) => {
    contentRef.current = content;
    hasUnsavedChanges.current = true;
    
    // 如果内容实际未改变，不触发保存
    if (JSON.stringify(lastSavedContentRef.current) === JSON.stringify(content)) {
      return;
    }
    
    // 备份到localStorage（即使是在自动保存前也做备份）
    if (typeof window !== 'undefined' && backupLocalContent) {
      backupContentToLocalStorage(content);
    }
    
    // 触发自动保存
    debouncedSave(content);
  }, [debouncedSave, backupContentToLocalStorage, backupLocalContent]);
  
  // 查询本地备份
  const checkLocalBackup = useCallback(() => {
    if (!backupLocalContent || typeof window === 'undefined') return null;
    
    try {
      const backupStr = localStorage.getItem(localStorageKey);
      if (!backupStr) return null;
      
      const backup = JSON.parse(backupStr);
      return backup;
    } catch (error) {
      console.error('读取本地备份失败:', error);
      return null;
    }
  }, [localStorageKey, backupLocalContent]);
  
  // 获取本地备份历史
  const getLocalBackupHistory = useCallback(() => {
    if (!backupLocalContent || typeof window === 'undefined') return [];
    
    try {
      const backupsStr = localStorage.getItem(`${localStorageKey}_backups`);
      if (!backupsStr) return [];
      
      return JSON.parse(backupsStr);
    } catch (error) {
      console.error('读取备份历史失败:', error);
      return [];
    }
  }, [localStorageKey, backupLocalContent]);
  
  // 恢复指定备份
  const restoreBackup = useCallback(async (backupData: any) => {
    if (!backupData) return false;
    
    try {
      // 更新内容引用
      contentRef.current = backupData.content;
      
      // 手动保存恢复的内容
      const result = await save(backupData.content);
      
      if (result) {
        console.log('备份恢复成功');
        return true;
      } else {
        console.error('备份恢复失败');
        return false;
      }
    } catch (error) {
      console.error('恢复备份出错:', error);
      return false;
    }
  }, [save]);
  
  // 清除本地备份
  const clearLocalBackup = useCallback(() => {
    if (!backupLocalContent || typeof window === 'undefined') return;
    
    try {
      localStorage.removeItem(localStorageKey);
      console.log('本地备份已清除');
    } catch (error) {
      console.error('清除本地备份失败:', error);
    }
  }, [localStorageKey, backupLocalContent]);
  
  // 检测是否有本地备份
  const hasLocalBackup = useCallback(() => {
    if (!backupLocalContent || typeof window === 'undefined') return false;
    
    try {
      const backup = localStorage.getItem(localStorageKey);
      return !!backup;
    } catch {
      return false;
    }
  }, [localStorageKey, backupLocalContent]);
  
  // 在页面卸载前尝试保存
  useEffect(() => {
    if (!enabled || !backupLocalContent) return;
    
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      // 检查是否有未保存的内容
      if (hasUnsavedChanges.current && contentRef.current) {
        // 在页面关闭前备份到localStorage
        backupContentToLocalStorage(contentRef.current);
        
        // 提示用户有未保存内容
        e.preventDefault();
        e.returnValue = '你有未保存的更改，确定要离开吗？';
        return e.returnValue;
      }
    };
    
    // 初始化时检查是否有本地备份
    const initialBackup = checkLocalBackup();
    if (initialBackup && initialBackup.projectId === projectId && initialBackup.documentId === documentId) {
      console.log('发现本地备份', initialBackup);
    }
    
    // 添加页面卸载事件监听
    window.addEventListener('beforeunload', handleBeforeUnload);
    
    // 清理函数
    return () => {
      // 页面卸载前取消所有挂起的自动保存
      debouncedSave.cancel();
      
      // 如果有未保存的更改，在组件卸载时尝试保存到localStorage
      if (hasUnsavedChanges.current && contentRef.current) {
        backupContentToLocalStorage(contentRef.current);
      }
      
      // 移除事件监听
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [enabled, projectId, documentId, debouncedSave, backupContentToLocalStorage, checkLocalBackup, backupLocalContent]);
  
  // 导出API
  return {
    status,
    lastSavedAt,
    documentVersion,
    conflictDetected,
    saveAttempts,
    hasUnsavedChanges: hasUnsavedChanges.current,
    
    // 动作
    save,
    triggerAutoSave,
    backupContentToLocalStorage,
    checkLocalBackup,
    clearLocalBackup,
    hasLocalBackup,
    getLocalBackupHistory,
    restoreBackup
  };
} 